package com.zzx.cursor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzx.cursor.entity.Consumer;
import com.zzx.cursor.mapper.CursorMapper;
import com.zzx.cursor.service.CursorService;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ArticleServiceImpl
 * @Description:
 * @Author zhouzhixin
 * @Date 2021/8/6
 * @Version 1.0
 */
@Service
public class CursorServiceImpl implements CursorService {

    private CursorMapper cursorMapper;

    @Autowired
    private void init(CursorMapper cursorMapper) {
        this.cursorMapper = cursorMapper;
    }

    /**
     * <p>此处流式查询需要添加事务注解来保证数据库的连接再查询方法结束之前不会关闭</p>
     * <p>需要注意事务的失效场景</p>
     *
     * @param page
     * @return java.lang.Long
     * @author zhouzhixin
     * @date 2021/8/9 9:37
     */
    @Override
    @Transactional
    public Long cursorTest(IPage<Consumer> page) {
        List<Consumer> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        page.setCurrent((page.getCurrent() - 1) * page.getSize());
        try (Cursor<Consumer> dataCursor = cursorMapper.cursorTest(page)) {
            for (Consumer consumer : dataCursor) {
                list.add(consumer);
                if (dataCursor.getCurrentIndex() == (10 - 1)) {
                    break;
                }
            }
            System.out.println("cursorTest:" + list.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        return end - start;
    }

    /**
     * <p>普通分页查询</p>
     *
     * @param page
     * @return java.lang.Long
     * @author zhouzhixin
     * @date 2021/8/9 9:39
     */
    @Override
    public Long normalTest(IPage<Consumer> page) {
        List<Consumer> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        page.setCurrent((page.getCurrent() - 1) * page.getSize());
        List<Consumer> dataList = cursorMapper.normalTest(page);
        for (Consumer consumer : dataList) {
            list.add(consumer);
            if (list.size() == 10) {
                break;
            }
        }
        System.out.println("normalTest:" + list.size());
        long end = System.currentTimeMillis();
        return end - start;
    }
}
